package com.oceansoft.mobile.biz.front.controller;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.biz.front.entity.AppPlugins;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.weixin.entity.WX_User;
import com.oceansoft.mobile.weixin.service.WechatService;
import com.oceansoft.mobile.weixin.util.SignUtil;
import com.oceansoft.mobile.weixin.util.WeixinUtil;

/**
 * Created by Administrator on 2016/1/20.
 */
@Controller
@RequestMapping("micro")
public class MicroPoliceController {
    @Resource
    private WechatService wechatService;
    
    @Resource
    private ICommonDao commonDao;

    @RequestMapping(value = "police", method = RequestMethod.GET)
    public String gotoMicroPoliceIndex(HttpServletRequest request, Model model) {
        String openId = (String) request.getSession().getAttribute("openId");
        /*if (StringUtils.isEmpty(openId)) {
            openId = request.getParameter("openId");
        }
        System.out.println(openId);
        request.getSession().setAttribute("openId", openId);*/
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
        	model.addAttribute("source", source);
        }
        return "weixin/index";
    }

    @RequestMapping(value = "sxbjym", method = RequestMethod.GET)
    public String gotoSuccessReport(HttpServletRequest request, Model model) {
        String bjguid = request.getParameter("bjguid");
        model.addAttribute("bjguid", bjguid);
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
        	model.addAttribute("source", source);
        }
        return "weixin/sxbjym";
    }

    @RequestMapping(value = "weixin/{pageName}", method = RequestMethod.GET)
    public String gotoPages(@PathVariable("pageName") String pageName,HttpServletRequest request, Model model) {
    	 String source = (String) request.getSession().getAttribute("source");
         if (StringUtils.isNotBlank(source)) {
         	model.addAttribute("source", source);
         }
        String location = (String) request.getSession().getAttribute("location");
        if (StringUtils.isNotBlank(location)) {
            model.addAttribute("location", location);
        }
        return "weixin/" + pageName;
    }

    @RequestMapping(value = "gotoPageWithUser/{pageName}")
    public String gotoPage(@PathVariable("pageName") String pageName, HttpSession session, HttpServletRequest request,
                           Model model) throws IllegalArgumentException, IOException {
        boolean b = WeixinUtil.checkIsLoginUser(request);
        if (!b) {
            model.addAttribute("openId", (String) session.getAttribute("openId"));
            model.addAttribute("gotoPage", "/micro/gotoPageWithUser/" + pageName);
            return "weixin/login/login";
        } else {
            Member member = (Member) session.getAttribute(Constant.SESSION_USER);
            model.addAttribute("userId", member.getGuid());
            model.addAttribute("openId", member.getOpenId());
            model.addAttribute("userName", member.getRealName());
            model.addAttribute("mobile", member.getMobile());
            model.addAttribute("address", member.getAddress());
            model.addAttribute("email", member.getEmail());
            model.addAttribute("idCard", member.getIdCard());
            String source = (String) request.getSession().getAttribute("source");
            if (StringUtils.isNotBlank(source)) {
            	model.addAttribute("source", source);
            }
            return "weixin/" + pageName;
        }

    }

    @RequestMapping(value = "gotoWithUser/{pageName}")
    public String gotowithPage(@PathVariable("pageName") String pageName, HttpSession session, HttpServletRequest request,
                               Model model) throws IllegalArgumentException, IOException {
        boolean b = WeixinUtil.checkIsLoginUser(request);
        if (!b) {
            model.addAttribute("openId", (String) session.getAttribute("openId"));
            model.addAttribute("gotoPage", "/micro/gotoWithUser/" + pageName);
            return "weixin/login/login";
        } else {
            Member member = (Member) session.getAttribute(Constant.SESSION_USER);

            model.addAttribute("data", member);

			/*model.addAttribute("userId",member.getGuid());
            model.addAttribute("openId",member.getOpenId());
			model.addAttribute("userName",member.getRealName());
			model.addAttribute("mobile",member.getMobile());*/
            String source = (String) request.getSession().getAttribute("source");
            if (StringUtils.isNotBlank(source)) {
            	model.addAttribute("source", source);
            }
            
            
            return "weixin/matters/" + pageName;
        }

    }

    @RequestMapping(value = "weixin/{type}/{id}", method = RequestMethod.GET)
    public String gotoPages(@PathVariable("type") int type, @PathVariable("id") int id, Model model, HttpServletRequest request) {
        String pageName = "";
        model.addAttribute("id", id);
        switch (type) {
            case 1:
                pageName = "bafwgsxq";
                break;
            case 2:
                pageName = "bapxgsxq";
                break;
            case 3:
                pageName = "jssggsxq";
                break;
            case 4:
                pageName = "ksglxq";
                break;
        }
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
        	model.addAttribute("source", source);
        }
        return "weixin/" + pageName;
    }

    @ResponseBody
    @RequestMapping(value = "putuser", method = POST)
    public Result putAppUser(HttpServletRequest request, Model model, HttpSession session) {
        Result r = new Result();
        String account = request.getParameter("account");
        if (StringUtils.isNotEmpty(account)) {
            JSON josnJson = JSON.parseObject(account);
            Member member = JSON.toJavaObject(josnJson, Member.class);
            session.setAttribute(Constant.SESSION_USER, member);
            r.setData(member);
        }
        return r;
    }
    /***
     * 需要登录的页面预先统一处理
     * by liujie
     *
     * @param state
     * @param request
     * @param model
     * @return
     */
    @Deprecated
    @RequestMapping(value = "gotoPageByUserAll/{state}", method = RequestMethod.GET)
    public String gotoPages(@PathVariable("state") String state,
                            HttpServletRequest request, Model model, HttpSession session) {
        model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
        model.addAttribute("state", state);
        String url =  Constant.stateMap.get(state);
        if(StringUtils.isEmpty(url))
        {
        	url =  Constant.stateMap.get("0");
        }
        model.addAttribute("url",url);
        Member member = (Member) session.getAttribute(Constant.SESSION_USER);
        model.addAttribute("data", member);
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
        	model.addAttribute("source", source);
        }
        return "weixin/redirectByUser";
    }

    /***
     * 外部页面跳转统一处理
     * 方便记录点击数量
     * by liujie
     *
     * @param state
     * @return
     */
    @RequestMapping(value = "redirect/{state}", method = RequestMethod.GET)
    public String redirectTo(@PathVariable("state") String state,HttpServletRequest request, Model model) {
        String url = Constant.stateMap.get(state);
        if (StringUtils.isEmpty(url)) {
            url = Constant.stateMap.get("0");
        }
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
        	//model.addAttribute("source", source);
        	if("0".equals(state))
        	{
        		source = "szgawx";
        	}
        	
        	if(url.indexOf("?")>=0)
        	{
        		url+="&source="+source;
        	}
        	else
        	{
        		url+="?source="+source;
        	}
        	
        }
        
        //重名查询不用拼接openId
        if(!"23".equals(state))
        {
	        if(url.indexOf("?")>=0)
	    	{
	    		url+="&openId="+request.getSession().getAttribute("openId");
	    	}
	    	else
	    	{
	    		url+="?openId="+request.getSession().getAttribute("openId");
	    	}
        }
        return "redirect:" + url;
    }


    /***
     * 外部页面跳转统一处理
     * 方便记录点击数量
     * by liujie
     *
     * @param state
     * @return
     */
    @RequestMapping(value = "redirect/{state}/{standardid}", method = RequestMethod.GET)
    public String redirectTo(@PathVariable("state") String state,@PathVariable("standardid") String standardid,HttpServletRequest request, Model model) {
        String url = Constant.stateMap.get(state);
        if (StringUtils.isEmpty(url)) {
            url = Constant.stateMap.get("0");
        }
        String source = (String) request.getSession().getAttribute("source");
        if (StringUtils.isNotBlank(source)) {
            //model.addAttribute("source", source);
            if("0".equals(state))
            {
                source = "szgawx";
            }

            if(url.indexOf("?")>=0)
            {
                url+="&source="+source;
            }
            else
            {
                url+="?source="+source;
            }

        }

        //重名查询不用拼接openId
        if(!"23".equals(state))
        {
            if(url.indexOf("?")>=0)
            {
                url+="&openId="+request.getSession().getAttribute("openId");
            }
            else
            {
                url+="?openId="+request.getSession().getAttribute("openId");
            }
        }
        //标准事项从request中拿到申报事项名称
        if(StringUtils.isNotBlank(standardid)){
            if(url.indexOf("?")>=0)
            {
                url+="&standardid="+standardid;
            }
            else
            {
                url+="?standardid="+standardid;
            }
        }
        return "redirect:" + url;
    }



    
    @RequestMapping(value = "app2Wx/{state}", method = RequestMethod.GET)
    public String app2Wx(@PathVariable("state") int state,HttpServletRequest request) {
    	//从appplugins中取得对应的url
    	String key = "AppPlugins";
    	Result r = null;
    	List<AppPlugins> list = null;
    	if (CacheBaseService.getInstance().exists(key)) {
            r = CacheBaseService.getInstance().getObject(key, Result.class);
            list = (List<AppPlugins>)    JSON.parseArray( r.getData().toString(), AppPlugins.class) ;
        }else
        {
        	 list = commonDao.loadList("select * from t_app_plugins ", ParameterizedBeanPropertyRowMapper.newInstance(AppPlugins.class));
        	 r = new Result();
             r.setData(list);
             CacheBaseService.getInstance().cache(key, r, 1f);
        }
    	
    	String url = "";
    	//用state找startPage
    	for (AppPlugins appPlugins : list) {
    		int id = appPlugins.getId();
    		if(id==state)
    		{
    			url = appPlugins.getPage();
    			break;
    		}
		}
    	
    	if(StringUtils.isEmpty(url))
    	{
    		url = Constant.stateMap.get(0);
    	}
        
        String source = request.getParameter("source");
        if (StringUtils.isNotBlank(source)) {
        	//model.addAttribute("source", source);
        	if(url.indexOf("?")>=0)
        	{
        		url+="&source="+source;
        	}
        	else
        	{
        		url+="?source="+source;
        	}
        }
        return "redirect:" + url;
    }
    
    //各个地区的关注扫码
    @RequestMapping(value = "gz/{area}", method = RequestMethod.GET)
    public String gz(@PathVariable("area") String area,HttpServletRequest request) {
    	//跳转到关注页面
    	String url = Constant.stateMap.get("-1");
    	//获取openId
    	String openId = (String)request.getSession().getAttribute("openId");
    	//记录下扫码人信息
    	String isgz = "0";
    	
    	String sql = "insert into t_wx_sm_user values (?,now(),?,?,"+isgz+")";
    	//判断当前openId是否已经关注
    	WX_User user = commonDao.loadOne("select * from wx_user t where t.openid=? and t.subscribe=1",  WX_User.getMapp(), openId);
//		   System.out.println("本地查询用户是否关注==="+user);
	  	if(null==user)
	  	{
	  		commonDao.update(sql, openId,null,area);
	  	}
	  	else
	  	{
	  		isgz = "1";
	  		Date d = new Date();
	  		d.setTime(user.getSubscribe_time());
	  		commonDao.update(sql, openId,d,area);
	  		url  = Constant.stateMap.get("0");
	  	}
        return "redirect:" + url;
    }
    

    /***
     * 重名查询
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "getPageWithToken/cmcx")
    public String redirectWithToken(HttpServletRequest request, Model model) {
        String url = "http://wjw.szgaj.cn/szgawx/micro/getPageWithToken/cmcx";
        String name = request.getParameter("name");
        if(StringUtils.isEmpty(name))
        {
        	name = (String)request.getSession().getAttribute("cmcx_name");
       	 	if(!StringUtils.isEmpty(name))
            {
       	 		request.getSession().removeAttribute("cmcx_name");
            }
        }
        
        String source = request.getParameter("source");
        if(StringUtils.isEmpty(source))
        {
        	source = (String)request.getSession().getAttribute("source");
       	 	if(!StringUtils.isEmpty(source))
            {
       	 		request.getSession().removeAttribute("source");
            }
        }
         
        
        
        if (StringUtils.isNotBlank(source)) {
        	model.addAttribute("source", source);
        	url += "?source="+source;
        }
//        System.out.println("重名查询url =====" + url);
        if(StringUtils.isEmpty(name))
        {
        	name = "";
        }
        	
//        System.out.println("重名查询name======"+name);
        String jsapiTicket = wechatService.getJsapiTicket();
        JSONObject json = SignUtil.getSignature(jsapiTicket, url);
        model.addAttribute("token", json);
        model.addAttribute("name", name);
//        System.out.println("表单提交过来 ======="+request.getParameter("name"));
// 	    System.out.println("   session cmcx==="+request.getSession().getAttribute("cmcx_name"));

        return "weixin/cmcx";
    }

    @RequestMapping(value = "redirectWithOpenId")
    public String redirectWithOpenId(HttpServletRequest request){
        String url = (String)request.getSession().getAttribute("url");
        return "redirect:" + url;
    }
}
